#!/usr/bin/env bash
set -e

exec 2>&1

APP=cargohold

# defaults
USER=${USER:-www-data}
CONFIG=${CONFIG:-/etc/$APP/.env}
HOME=${APP_HOME:-/opt/$APP}
BIN=$HOME/bin/$APP

# we need KHAN_DOMAIN before sourcing $CONFIG
source <(khan --silent metadata --multiline)

if [ ! -f $CONFIG ]; then exec chpst -u $USER get_config; fi
source $CONFIG

AWS_ACCESS_KEY_ID=${CARGOHOLD_AWS_ACCESS_KEY_ID:+--aws-key-id=$CARGOHOLD_AWS_ACCESS_KEY_ID}
AWS_SECRET_ACCESS_KEY=${CARGOHOLD_AWS_SECRET_ACCESS_KEY:+--aws-secret-key=$CARGOHOLD_AWS_SECRET_ACCESS_KEY}

export LOG_LEVEL=${CARGOHOLD_LOG_LEVEL:-Info}
export LOG_BUFFER=${CARGOHOLD_LOG_BUFFER:-4096}
export LOG_NETSTR=${CARGOHOLD_LOG_NETSTR:-True}

cd $HOME

ulimit -n 65536

exec chpst -u $USER \
    $BIN \
    --host=${CARGOHOLD_HOST:-'127.0.0.1'} \
    --port=${CARGOHOLD_PORT?'unset'} \
    ${AWS_ACCESS_KEY_ID} \
    ${AWS_SECRET_ACCESS_KEY} \
    --aws-s3-endpoint=${CARGOHOLD_AWS_S3_ENDPOINT:-'https://s3.eu-west-1.amazonaws.com'} \
    --aws-s3-bucket=${CARGOHOLD_AWS_S3_BUCKET?'unset'} \
    --aws-cloudfront-domain=${CARGOHOLD_AWS_CLOUDFRONT_DOMAIN?'unset'} \
    --aws-cloudfront-keypair-id=${CARGOHOLD_AWS_CLOUDFRONT_KEYPAIR_ID?'unset'} \
    --aws-cloudfront-private-key=${CARGOHOLD_AWS_CLOUDFRONT_PRIVATEKEY?'unset'} \
    --max-total-bytes=${CARGOHOLD_MAX_TOTAL_BYTES?'unset'} \
    --download-link-ttl=${CARGOHOLD_DOWNLOAD_LINK_TTL:-300}
